# -*- coding: utf-8 -*-

from __future__ import absolute_import, print_function, unicode_literals

import json
import math
import random
import re
import time

import requests

from jiandan.const import agents, JianDanConst
from jiandan.exceptions import JianDanException, JianDanRequestsException, JianDanVcodeOcrException
from jiandan.five import must_str, quote
# from jiandan.identify_image import (identify_image_callback_by_hand, unlock_jiandan_callback_example, unlock_jiandan_callback_example, jd_cache)
from jiandan.identify_image import jd_cache
from jiandan.request import JianDanRequest
from jiandan.structuring import JianDanStructuring
from jiandan.tools import may_int


class JianDanAPI(object):
    def __init__(self, captcha_break_time=1, headers=None, **kwargs):
        """初始化参数

        Parameters
        ----------
        captcha_break_time : int
            验证码输入错误重试次数
        proxies : dict
            代理
        timeout : float
            超时时间
        """
        assert isinstance(captcha_break_time, int) and 0 < captcha_break_time < 20

        self.captcha_break_times = captcha_break_time
        self.requests_kwargs = kwargs
        self.headers = headers
        if self.headers:
            self.headers['User-Agent'] = random.choice(agents)
        else:
            self.headers = {'User-Agent': random.choice(agents)}

    def __set_cookie(self, suv=None, snuid=None, referer=None):
        suv = jd_cache.get('suv') if suv is None else suv
        snuid = jd_cache.get('snuid') if snuid is None else snuid
        _headers = {'Cookie': 'SUV={};SNUID={};'.format(suv, snuid)}
        if referer is not None:
            _headers['Referer'] = referer
        return _headers

    def __set_cache(self, suv, snuid):
        jd_cache.set('suv', suv)
        jd_cache.set('snuid', snuid)

    def __get(self, url, session, headers):
        h = {}
        if headers:
            for k, v in headers.items():
                h[k] = v
        if self.headers:
            for k, v in self.headers.items():
                h[k] = v
        resp = session.get(url, headers=h, **self.requests_kwargs)

        if not resp.ok:
            raise JianDanRequestsException('JianDanAPI get error', resp)

        return resp



    def __get_by_unlock(self, url, referer=None, unlock_platform=None, unlock_callback=None,
                         session=None):
        assert unlock_platform is None or callable(unlock_platform)

        assert unlock_callback is None or callable(unlock_callback)
        if not session:
            session = requests.session()
        resp = self.__get(url, session, headers=self.__set_cookie(referer=referer))
        resp.encoding = 'utf-8'
        headers = self.__set_cookie(referer=referer)
        headers['User-Agent'] = 'Mozilla/5.0 (Windows NT 6.1; WOW64)'
        resp = self.__get(url, session, headers)
        resp.encoding = 'utf-8'
        return resp

    def __format_url(self, url, referer, text, unlock_callback=None, identify_image_callback=None, session=None):
        def _parse_url(url, pads):
            b = math.floor(random.random() * 100) + 1
            a = url.find("url=")
            c = url.find("&k=")
            if a != -1 and c == -1:
                sum = 0
                for i in list(pads) + [a, b]:
                    sum += int(must_str(i))
                a = url[sum]

            return '{}&k={}&h={}'.format(url, may_int(b), may_int(a))

        if url.startswith('/link?url='):
            url = 'https://weixin.sogou.com{}'.format(url)

            pads = re.findall(r'href\.substr\(a\+(\d+)\+parseInt\("(\d+)"\)\+b,1\)', text)
            url = _parse_url(url, pads[0] if pads else [])
            resp = self.__get_by_unlock(url,
                                        referer=referer,
                                        unlock_platform=self.__unlock_sogou,
                                        unlock_callback=unlock_callback,
                                        identify_image_callback=identify_image_callback,
                                        session=session)
            uri = ''
            base_url = re.findall(r'var url = \'(.*?)\';', resp.text)
            if base_url and len(base_url) > 0:
                uri = base_url[0]

            mp_url = re.findall(r'url \+= \'(.*?)\';', resp.text)
            if mp_url:
                uri = uri + ''.join(mp_url)
            url = uri.replace('@', '')
        return url


    def get_ooxx_img(self):
        """
        获取ooxx （妹子图的）图片
        不过目前只能获取到第一页的图片 因为煎蛋好像做了什么
        地址是这样的http://jandan.net/ooxx/MjAyMDA2MjMtMTIz#comments
        :return:
        dict or None
            {
                'author_name': 作者名称,
                'image_src': 图片地址,

            }
        """
        url = JianDanRequest.gen_ooxx_url()
        session = requests.session()
        resp = self.__get_by_unlock(url, session=session)
        img_list = JianDanStructuring.get_ooxx_img(resp.text)
        return img_list


    def get_new_100_info(self):
        """获取new前100条数据
        Parameters
        ----------
        Returns
        -------
        dict or None
            {
                'author_name': 作者名称,
                'author_url': 作者_url,
                'create_datetime': 创建时间,
                'title': 标题,
                'content': 内容
            }
        """
        all_new_100 = []
        url = JianDanRequest.gen_new_100_url()
        session = requests.session()
        resp = self.__get_by_unlock(url, session=session)
        new_100_list = JianDanStructuring.get_new_100_url(resp.text)
        for li in new_100_list:
            li_url = JianDanRequest.gen_new_info_url(li['url'])
            response = self.__get_by_unlock(li_url, session=session)
            all_new_100.append(JianDanStructuring.get_new_url(response.text))
        return all_new_100
